using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;

namespace ManagerUnitTests
{
    public static class ControllerExtensions
    {
        //Enforeces model validation during testing. This is required because model binding doesn't occur in 
        //during testing which means that ModelState.IsValid is always true
        public static HttpResponseMessage CallWithModelValidation<C, R, T>(this C controller
                                                                           , Func<C, R> action
                                                                           , T model)
            where C : ApiController
            where R : HttpResponseMessage
            where T : class
        {
            DataAnnotationsModelValidatorProvider provider = new DataAnnotationsModelValidatorProvider();

            IEnumerable<ModelMetadata> metadata = ModelMetadataProviders
                .Current
                .GetMetadataForProperties(model, typeof(T));
            foreach (ModelMetadata modelMetadata in metadata)
            {
                IEnumerable<ModelValidator> validators = provider
                    .GetValidators(modelMetadata, new ControllerContext());

                foreach (ModelValidator validator in validators)
                {
                    IEnumerable<ModelValidationResult> results = validator.Validate(model);
                    foreach (ModelValidationResult result in results)
                        controller.ModelState.AddModelError(modelMetadata.PropertyName, result.Message);
                }
            }
            return action(controller);
        }
    }
}